package org.itzheng.myrxframe.base;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.widget.Toast;

import org.itzheng.and.activity.ItActivity;
import org.itzheng.and.baseutils.ui.UIUtils;
import org.itzheng.myrxframe.http.rxjava.IRxNet;
import org.itzheng.myrxframe.ui.toast.ActivityToastPopup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Title:<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-4-9.
 */
public class BaseActivity extends ItActivity implements IRxNet {
    /**
     * 用于存储Rx引用
     */
    private List<Disposable> disposables = new ArrayList<>();
    private HashMap<Observer, Disposable> disposableHashMap = new HashMap<>();

    public void addDisposable(Observer observer, Disposable disposable) {
        if (observer == null) {
            addDisposable(disposable);
        } else {
            disposableHashMap.put(observer, disposable);
        }
    }

    /**
     * 是否显示返回键，默认不显示
     *
     * @param isShow
     */
    public void showBack(boolean isShow) {
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(isShow);
            actionBar.setDisplayHomeAsUpEnabled(isShow);
        }
    }

    /**
     * 监听返回键事件
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void addDisposable(Disposable disposable) {
        if (disposable != null) {
            disposables.add(disposable);
        }
    }

    @Override
    public void removeDisposable(Observer observer) {
        Disposable disposable = disposableHashMap.get(observer);
        disposableHashMap.remove(observer);
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribeRx();
    }

    protected void unSubscribeRx() {
        for (Disposable disposable : disposables) {
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        disposables.clear();
        for (Map.Entry<Observer, Disposable> entry : disposableHashMap.entrySet()) {
            Disposable disposable = entry.getValue();
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        disposableHashMap.clear();
    }

    ActivityToastPopup toastPopup;

    /**
     * 显示toast，如果系统默认的能使用则使用系统默认的，如果不能使用则调用自定义
     *
     * @param string
     */
    public void showToast(String string) {
        //创建Popup必须Activity渲染完毕才行
        if (!hasWindowFocus() || ActivityToastPopup.isSystemToast(getApplicationContext())) {
            UIUtils.showToast(string);
            return;
        }
        if (toastPopup == null) {
            toastPopup = new ActivityToastPopup(this);
        }
        toastPopup.makeText(string);
        if (!toastPopup.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toastPopup.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, dip2px(getApplicationContext(), 64)
                            + getNavigationBarHeight(BaseActivity.this));

                }
            });
        }
    }

    /**
     * dip转换px
     */
    public static int dip2px(Context context, int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * 获取导航栏的高度，如果有没有导航栏则返回0
     *
     * @param activity
     * @return
     */
    public static int getNavigationBarHeight(Activity activity) {
        if (!isNavigationBarShow(activity)) {
            return 0;
        }
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public static boolean isNavigationBarShow(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = context.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (menu || back) {
                return false;
            } else {
                return true;
            }
        }
    }
}
